<template>
  <div class="project-detail-container">
    <div class="page-header">
      <div class="page-title">
        <el-button icon="el-icon-back" type="link" @click="goBack">返回</el-button>
        <h2>{{ projectName }}</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateTaskDialog">
          创建任务
        </el-button>
        <el-button 
          type="success" 
          @click="showEditProjectDialog" 
          :disabled="!isOwnerOrCreator" 
          :title="!isOwnerOrCreator ? '只有项目负责人或创建者可以编辑项目' : ''"
        >
          编辑项目
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="project-info">
      <template #header>
        <div class="card-header">
          <span>项目信息</span>
        </div>
      </template>
      <div v-if="project">
        <div class="info-item">
          <span class="label">项目ID：</span>
          <span>{{ project.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">项目名称：</span>
          <span>{{ project.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">项目描述：</span>
          <span>{{ project.description }}</span>
        </div>
        <div class="info-item">
          <span class="label">创建时间：</span>
          <span>{{ project.created_at }}</span>
        </div>
        <div class="info-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(project.status)">
            {{ getStatusText(project.status) }}
          </el-tag>
        </div>
        <div class="info-item">
          <span class="label">项目创建人：</span>
          <span v-if="project.creator_username">{{ project.creator_username }}</span>
          <span v-else>未知</span>
        </div>
        <div class="info-item">
          <span class="label">项目负责人：</span>
          <span v-if="project.owner_username">{{ project.owner_username }}</span>
          <span v-else>未知</span>
        </div>
        <div class="info-item">
          <span class="label">您的角色：</span>
          <el-tag :type="getUserRoleType(project.user_role)">
            {{ getUserRoleText(project.user_role) }}
          </el-tag>
        </div>
        
        <!-- Git仓库信息 -->
        <div class="info-section">
          <h3>Git仓库信息</h3>
          <template v-if="project.git_repository_url">
            <div class="info-item">
              <span class="label">仓库地址：</span>
              <span>{{ project.git_repository_url }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户名：</span>
              <span>{{ project.git_username || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">访问凭证：</span>
              <span>{{ project.git_password ? '已设置' : '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">默认分支：</span>
              <span>{{ project.git_branch || 'main' }}</span>
            </div>
          </template>
          <div v-else class="empty-git-info">
            未配置Git仓库信息，
            <el-button 
              type="link" 
              @click="showEditProjectDialog('git')" 
              :disabled="!isOwnerOrCreator"
              :title="!isOwnerOrCreator ? '只有项目负责人或创建者可以编辑项目' : ''"
            >
              点击设置
            </el-button>
          </div>
        </div>
        
        <!-- 项目文件夹信息 -->
        <div class="info-section">
          <h3>项目文件夹信息</h3>
          <template v-if="project.project_folder_path">
            <div class="info-item">
              <span class="label">文件夹路径：</span>
              <span>{{ project.project_folder_path }}</span>
            </div>
          </template>
          <div v-else class="empty-info">
            未配置项目文件夹路径，
            <el-button 
              type="link" 
              @click="showEditProjectDialog('folder')" 
              :disabled="!isOwnerOrCreator"
              :title="!isOwnerOrCreator ? '只有项目负责人或创建者可以编辑项目' : ''"
            >
              点击设置
            </el-button>
          </div>
        </div>
        
        <!-- 数据库连接信息 -->
        <div class="info-section">
          <h3>数据库连接信息</h3>
          <template v-if="project.db_host">
            <div class="info-item">
              <span class="label">数据库类型：</span>
              <span>{{ project.db_type || 'PostgreSQL' }}</span>
            </div>
            <div class="info-item">
              <span class="label">主机地址：</span>
              <span>{{ project.db_host }}</span>
            </div>
            <div class="info-item">
              <span class="label">端口：</span>
              <span>{{ project.db_port || '5432' }}</span>
            </div>
            <div class="info-item">
              <span class="label">数据库名：</span>
              <span>{{ project.db_name }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户名：</span>
              <span>{{ project.db_username || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">密码：</span>
              <span>{{ project.db_password ? '已设置' : '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">Schema：</span>
              <span>{{ project.db_schema || 'public' }}</span>
            </div>
          </template>
          <div v-else class="empty-info">
            未配置数据库连接信息，
            <el-button 
              type="link" 
              @click="showEditProjectDialog('database')" 
              :disabled="!isOwnerOrCreator"
              :title="!isOwnerOrCreator ? '只有项目负责人或创建者可以编辑项目' : ''"
            >
              点击设置
            </el-button>
          </div>
        </div>
      </div>
      <el-empty v-else-if="!loading" description="无法获取项目信息"></el-empty>
    </el-card>

    <div class="section-title">
      <h3>项目成员</h3>
      <el-button 
        v-if="project && project.can_edit" 
        type="primary" 
        size="small" 
        @click="showAddMemberDialog">
        添加成员
      </el-button>
    </div>

    <el-card v-loading="membersLoading">
      <el-table :data="members" style="width: 100%">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column label="角色" width="180">
          <template #default="scope">
            <div class="role-tag-container">
              <el-tag 
                v-if="scope.row.is_creator" 
                type="danger" 
                effect="dark" 
                class="role-tag">
                创建人
              </el-tag>
              <el-tag 
                v-if="scope.row.is_owner" 
                type="warning" 
                effect="dark" 
                class="role-tag">
                负责人
              </el-tag>
              <el-tag 
                v-if="scope.row.role" 
                type="info" 
                class="role-tag">
                {{ getMemberRoleText(scope.row.role) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="加入时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.added_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" v-if="project && project.can_edit">
          <template #default="scope">
            <el-button 
              v-if="!scope.row.is_creator && !scope.row.is_owner && currentUserId !== scope.row.id"
              type="danger" 
              size="small" 
              @click="removeMember(scope.row)">
              移除
            </el-button>
            <el-button 
              v-if="!scope.row.is_creator && !scope.row.is_owner && currentUserId !== scope.row.id"
              type="primary" 
              size="small" 
              @click="setAsOwner(scope.row)">
              设为负责人
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="members.length === 0" description="暂无项目成员"></el-empty>
    </el-card>

    <div class="section-title">
      <h3>任务列表</h3>
    </div>

    <el-card v-loading="tasksLoading">
      <template v-if="tasks && tasks.length > 0">
        <el-table :data="tasks" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="任务标题" />
          <el-table-column prop="description" label="任务描述" show-overflow-tooltip />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getTaskStatusType(scope.row.status)">
                {{ getTaskStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewTask(scope.row.id)"
              >
                查看
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="confirmDeleteTask(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-empty v-else-if="!tasksLoading" description="暂无任务，请使用「创建任务」按钮添加新任务">
        <template #description>
          <div>
            <p>暂无任务，请使用「创建任务」按钮添加新任务</p>
            <p v-if="tasks" style="color: #909399; font-size: 12px;">当前任务数量: {{ tasks.length }}</p>
          </div>
        </template>
      </el-empty>
    </el-card>

    <!-- 创建任务对话框 -->
    <el-dialog
      v-model="createTaskDialogVisible"
      title="创建新任务"
      width="500px"
    >
      <el-form 
        ref="createTaskFormRef" 
        :model="createTaskForm" 
        :rules="createTaskRules"
        label-width="80px"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="createTaskForm.title" placeholder="请输入任务标题"></el-input>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input 
            v-model="createTaskForm.description" 
            type="textarea" 
            rows="6"
            placeholder="请输入任务详细描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createTaskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateTaskForm" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 编辑项目对话框 -->
    <el-dialog
      v-model="editProjectDialogVisible"
      title="编辑项目信息"
      width="650px"
    >
      <el-form 
        ref="editProjectFormRef" 
        :model="editProjectForm" 
        :rules="editProjectRules"
        label-width="120px"
      >
        <el-tabs v-model="activeFormTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="editProjectForm.name" placeholder="请输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="项目描述" prop="description">
              <el-input 
                v-model="editProjectForm.description" 
                type="textarea" 
                rows="4"
                placeholder="请输入项目描述"
              ></el-input>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="Git仓库信息" name="git">
            <el-form-item label="仓库地址" prop="git_repository_url">
              <el-input v-model="editProjectForm.git_repository_url" placeholder="例如: https://github.com/username/repo.git"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="git_username">
              <el-input v-model="editProjectForm.git_username" placeholder="Git用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="git_password">
              <el-input type="password" v-model="editProjectForm.git_password" placeholder="Git密码或访问令牌，留空保持不变"></el-input>
              <div class="form-tip">密码会被安全存储，用于AI自动操作Git仓库</div>
            </el-form-item>
            <el-form-item label="分支" prop="git_branch">
              <el-input v-model="editProjectForm.git_branch" placeholder="Git分支，默认为main"></el-input>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="项目文件夹" name="folder">
            <el-form-item label="项目路径" prop="project_folder_path">
              <el-input v-model="editProjectForm.project_folder_path" placeholder="请输入项目文件夹的完整路径"></el-input>
              <div class="form-tip">例如: /path/to/project 或 C:\path\to\project</div>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="数据库信息" name="database">
            <el-form-item label="数据库类型" prop="db_type">
              <el-select v-model="editProjectForm.db_type" placeholder="请选择数据库类型" style="width: 100%;">
                <el-option label="PostgreSQL" value="postgresql"></el-option>
                <el-option label="MySQL" value="mysql"></el-option>
                <el-option label="SQLite" value="sqlite"></el-option>
                <el-option label="Oracle" value="oracle"></el-option>
                <el-option label="SQL Server" value="sqlserver"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="主机地址" prop="db_host">
              <el-input v-model="editProjectForm.db_host" placeholder="数据库主机地址，例如: localhost"></el-input>
            </el-form-item>
            
            <el-form-item label="端口" prop="db_port">
              <el-input-number v-model="editProjectForm.db_port" :min="1" :max="65535" placeholder="数据库端口" style="width: 100%;"></el-input-number>
              <div class="form-tip">PostgreSQL默认为5432，MySQL默认为3306</div>
            </el-form-item>
            
            <el-form-item label="数据库名" prop="db_name">
              <el-input v-model="editProjectForm.db_name" placeholder="数据库名称"></el-input>
            </el-form-item>
            
            <el-form-item label="Schema" prop="db_schema">
              <el-input v-model="editProjectForm.db_schema" placeholder="数据库Schema，默认为public"></el-input>
            </el-form-item>
            
            <el-form-item label="用户名" prop="db_username">
              <el-input v-model="editProjectForm.db_username" placeholder="数据库用户名"></el-input>
            </el-form-item>
            
            <el-form-item label="密码" prop="db_password">
              <el-input type="password" v-model="editProjectForm.db_password" placeholder="数据库密码，留空保持不变"></el-input>
              <div class="form-tip">密码会被安全存储，用于AI自动操作数据库</div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editProjectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditProjectForm" :loading="updateLoading">
            保存全部设置
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加成员对话框 -->
    <el-dialog
      v-model="addMemberDialogVisible"
      title="添加项目成员"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
      append-to-body
    >
      <div class="add-member-form">
        <el-form 
          ref="addMemberFormRef" 
          :model="addMemberForm" 
          :rules="addMemberRules"
          label-position="top"
        >
          <el-form-item label="选择用户" prop="user_id">
            <el-select 
              v-model="addMemberForm.user_id" 
              placeholder="请选择用户" 
              filterable 
              class="full-width-select"
              teleported
              :popper-append-to-body="true"
            >
              <el-option
                v-for="user in availableUsers"
                :key="user.id"
                :label="user.username"
                :value="user.id"
              >
                <div class="user-option">
                  <span class="username">{{ user.username }}</span>
                  <span v-if="user.email" class="email">({{ user.email }})</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="角色" prop="role">
            <el-select 
              v-model="addMemberForm.role" 
              placeholder="请选择角色"
              class="full-width-select"
              teleported
              :popper-append-to-body="true"
            >
              <el-option label="普通成员" value="member"></el-option>
              <el-option label="管理员" value="manager"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddMemberForm" :loading="addingMember">
            确认添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDatetime } from '../../utils/helpers'

export default {
  name: 'ProjectDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  components: {
  },
  setup(props) {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    const createTaskFormRef = ref(null)
    const editProjectFormRef = ref(null)
    const addMemberFormRef = ref(null)
    
    // 项目数据
    const project = computed(() => store.state.currentProject)
    const projectName = computed(() => project.value?.name || '项目详情')
    const loading = computed(() => store.getters.isLoading('currentProject'))
    
    // 任务数据
    const tasks = computed(() => store.state.projectTasks || [])
    const tasksLoading = computed(() => store.getters.isLoading('projectTasks'))
    
    // 当前用户ID
    const currentUserId = computed(() => {
      if (store.state.user && 'user_id' in store.state.user) {
        return store.state.user.user_id
      }
      // 后备兼容方案，兼容旧版数据结构
      return store.state.user?.id
    })
    
    // 项目成员数据
    const members = computed(() => store.state.projectMembers || [])
    const membersLoading = computed(() => store.getters.isLoading('projectMembers'))
    
    // 全部用户列表（用于添加成员选择）
    const allUsers = computed(() => store.state.users || [])
    const availableUsers = computed(() => {
      // 先深入打印当前成员和所有用户，便于排查问题
      console.log('当前项目所有成员:', members.value);
      console.log('所有系统用户:', allUsers.value);
      
      try {
        // 过滤掉已经是项目成员的用户
        if (!Array.isArray(members.value) || !Array.isArray(allUsers.value)) {
          console.warn('成员或用户列表不是数组:', {
            members: members.value,
            users: allUsers.value
          });
          return [];
        }
        
        // 将成员ID转换为字符串，确保比较一致性
        const memberIds = members.value
          .filter(m => m && m.id !== undefined && m.id !== null)
          .map(m => String(m.id));
        
        console.log('现有成员IDs (转换后):', memberIds);
        
        // 过滤出不在当前项目成员中的用户
        const available = allUsers.value.filter(user => {
          if (!user || user.id === undefined || user.id === null) {
            return false;
          }
          const userId = String(user.id);
          return !memberIds.includes(userId);
        });
        
        console.log('可用用户列表:', available);
        return available;
      } catch (error) {
        console.error('处理可用用户列表时出错:', error);
        return [];
      }
    })
    
    // 创建任务表单
    const createTaskDialogVisible = ref(false)
    const createTaskForm = ref({
      title: '',
      description: ''
    })
    const createTaskRules = {
      title: [
        { required: true, message: '请输入任务标题', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入任务描述', trigger: 'blur' },
        { min: 5, message: '任务描述不能少于5个字符', trigger: 'blur' }
      ]
    }
    const submitting = ref(false)
    
    // 编辑项目表单
    const editProjectDialogVisible = ref(false)
    const activeFormTab = ref('basic')
    const editProjectForm = ref({
      name: '',
      description: '',
      git_repository_url: '',
      git_username: '',
      git_password: '', // 留空表示不修改密码
      git_branch: '',
      project_folder_path: '',
      db_type: 'postgresql',
      db_host: '',
      db_port: 5432,
      db_name: '',
      db_username: '',
      db_password: '', // 留空表示不修改密码
      db_schema: 'public'
    })
    const editProjectRules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
      ],
      git_repository_url: [
        { pattern: /^(https?:\/\/|git@).*\.git$/, message: '请输入有效的Git仓库地址', trigger: 'blur' }
      ],
      git_branch: [
        { pattern: /^[a-zA-Z0-9_\-\.\/]+$/, message: '分支名称格式不正确', trigger: 'blur' }
      ],
      project_folder_path: [
        { max: 500, message: '路径长度不能超过500个字符', trigger: 'blur' }
      ],
      db_type: [
        { required: false, message: '请选择数据库类型', trigger: 'blur' }
      ],
      db_host: [
        { required: false, message: '请输入数据库主机地址', trigger: 'blur' }
      ],
      db_port: [
        { required: false, message: '请输入数据库端口', trigger: 'blur' },
        { type: 'number', message: '端口必须是数字', trigger: 'blur' }
      ],
      db_name: [
        { required: false, message: '请输入数据库名称', trigger: 'blur' }
      ],
      db_username: [
        { required: false, message: '请输入数据库用户名', trigger: 'blur' }
      ],
      db_password: [
        { max: 50, message: '密码长度不能超过50个字符', trigger: 'blur' }
      ],
      db_schema: [
        { max: 50, message: 'Schema长度不能超过50个字符', trigger: 'blur' }
      ]
    }
    const updateLoading = computed(() => store.getters.isLoading('updateProject'))
    
    // 添加成员表单
    const addMemberDialogVisible = ref(false)
    const addMemberForm = ref({
      user_id: '',
      role: 'member'
    })
    const addMemberRules = {
      user_id: [
        { required: true, message: '请选择用户', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'blur' }
      ]
    }
    const addingMember = ref(false)
    
    // 获取项目详情和任务列表
    const fetchProjectData = async () => {
      try {
        console.log('开始获取项目详情...')
        // 获取项目详情
        await store.dispatch('fetchProjectDetail', props.id)
        console.log('项目详情获取成功:', store.state.currentProject)
        
        console.log('开始获取项目任务列表...')
        // 获取项目任务列表
        await store.dispatch('fetchProjectTasks', props.id)
        console.log('项目任务列表获取成功:', store.state.projectTasks)
        
        console.log('开始获取项目成员...')
        // 获取项目成员
        await store.dispatch('fetchProjectMembers', props.id)
        console.log('项目成员获取成功:', store.state.projectMembers)
        
        console.log('开始获取所有用户...')
        // 获取所有用户（用于添加成员）
        await store.dispatch('fetchUsers')
        console.log('所有用户获取成功')
      } catch (error) {
        ElMessage.error(`获取项目信息失败: ${error.message}`)
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return formatDatetime(dateString)
    }
    
    // 创建任务相关
    const showCreateTaskDialog = () => {
      createTaskForm.value = {
        title: '',
        description: ''
      }
      createTaskDialogVisible.value = true
    }
    
    // 提交创建任务表单
    const submitCreateTaskForm = async () => {
      if (!createTaskFormRef.value) return
      
      await createTaskFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            console.log('开始创建任务...')
            await store.dispatch('createProjectTask', {
              projectId: props.id,
              taskData: createTaskForm.value
            })
            ElMessage.success('任务创建成功')
            createTaskDialogVisible.value = false
            console.log('开始重新获取任务列表...')
            await store.dispatch('fetchProjectTasks', props.id)
            console.log('任务列表已更新')
          } catch (error) {
            console.error('创建任务失败:', error)
            ElMessage.error(`创建失败: ${error.message}`)
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 编辑项目相关
    const showEditProjectDialog = (tab = 'basic') => {
      if (!project.value) return
      
      // 根据传入的tab设置激活的标签页
      activeFormTab.value = tab || 'basic'
      
      editProjectForm.value = {
        name: project.value.name || '',
        description: project.value.description || '',
        git_repository_url: project.value.git_repository_url || '',
        git_username: project.value.git_username || '',
        git_password: '', // 密码字段留空，表示不修改
        git_branch: project.value.git_branch || 'main',
        project_folder_path: project.value.project_folder_path || '',
        db_type: project.value.db_type || 'postgresql',
        db_host: project.value.db_host || '',
        db_port: project.value.db_port || 5432,
        db_name: project.value.db_name || '',
        db_username: project.value.db_username || '',
        db_password: '', // 密码字段留空，表示不修改
        db_schema: project.value.db_schema || 'public'
      }
      editProjectDialogVisible.value = true
    }
    
    // 提交编辑项目表单
    const submitEditProjectForm = async () => {
      if (!editProjectFormRef.value) return
      
      await editProjectFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 检查用户是否有权限编辑项目
            if (!isOwnerOrCreator.value) {
              ElMessage.error('只有项目负责人或创建者可以编辑项目')
              editProjectDialogVisible.value = false
              return
            }
            
            // 构建更新数据，如果密码为空则不更新密码
            const updateData = { ...editProjectForm.value }
            
            // 处理密码字段
            if (!updateData.git_password) {
              delete updateData.git_password
            }
            if (!updateData.db_password) {
              delete updateData.db_password
            }
            
            // 如果数据库信息不完整，根据字段依赖关系做调整
            const hasDbInfo = updateData.db_host && updateData.db_name
            
            if (!hasDbInfo) {
              // 如果没有设置数据库主机或名称，清除所有数据库相关字段
              delete updateData.db_host
              delete updateData.db_port
              delete updateData.db_name
              delete updateData.db_username
              delete updateData.db_password
              delete updateData.db_schema
              delete updateData.db_type
            }
            
            // 如果Git仓库地址为空，清除Git相关字段
            if (!updateData.git_repository_url) {
              delete updateData.git_username
              delete updateData.git_password
              delete updateData.git_branch
            }
            
            ElMessage.info('正在保存项目信息...')
            
            // 调试日志: 记录完整的项目更新数据
            console.log('调试: 项目更新请求数据', JSON.stringify(updateData, null, 2))
            
            await store.dispatch('updateProject', {
              projectId: props.id,
              projectData: updateData
            })
            
            // 调试日志: 记录更新成功
            console.log('调试: 项目更新成功，项目ID:', props.id)
            
            ElMessage.success('项目所有信息更新成功')
            editProjectDialogVisible.value = false
            
            // 刷新项目数据
            await fetchProjectData()
          } catch (error) {
            // 显示详细错误信息
            const errorMsg = error.message || '更新失败，请稍后重试'
            ElMessage.error(errorMsg)
            
            // 如果是权限问题，自动关闭对话框
            if (errorMsg.includes('权限') || errorMsg.includes('负责人')) {
              editProjectDialogVisible.value = false
            }
          }
        } else {
          // 表单验证失败
          ElMessage.warning('请正确填写必填字段')
        }
      })
    }
    
    // 查看任务详情
    const viewTask = (id) => {
      router.push(`/tasks/${id}`)
    }
    
    // 获取项目状态类型和文本
    const getStatusType = (status) => {
      switch (status) {
        case 'active': return 'success'
        case 'archived': return 'info'
        case 'completed': return 'primary'
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'active': return '活跃'
        case 'archived': return '已归档'
        case 'completed': return '已完成'
        default: return status
      }
    }
    
    // 获取任务状态类型和文本
    const getTaskStatusType = (status) => {
      switch (status) {
        case 'pending': return 'info'
        case 'in_progress': return 'warning'
        case 'completed': return 'success'
        default: return 'info'
      }
    }
    
    const getTaskStatusText = (status) => {
      switch (status) {
        case 'pending': return '待开始'
        case 'in_progress': return '进行中'
        case 'completed': return '已完成'
        default: return status
      }
    }
    
    // 确认删除任务
    const confirmDeleteTask = async (task) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除任务"${task.title}"吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await store.dispatch('deleteProjectTask', {
          projectId: props.id,
          taskId: task.id
        })
        ElMessage.success('任务删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`删除失败: ${error.message}`)
        }
      }
    }
    
    // 获取用户角色类型和文本
    const getUserRoleType = (role) => {
      switch (role) {
        case 'creator': return 'success'
        case 'owner': return 'warning'
        case 'member': return 'info'
        case 'manager': return 'primary'
        default: return 'info'
      }
    }
    
    const getUserRoleText = (role) => {
      switch (role) {
        case 'creator': return '创建人'
        case 'owner': return '负责人'
        case 'member': return '普通成员'
        case 'manager': return '管理员'
        default: return role
      }
    }
    
    // 获取成员角色文本
    const getMemberRoleText = (role) => {
      switch (role) {
        case 'member': return '普通成员'
        case 'manager': return '管理员'
        default: return role
      }
    }
    
    // 显示添加成员对话框
    const showAddMemberDialog = async () => {
      try {
        // 提前重置表单
        addMemberForm.value = {
          user_id: '',
          role: 'member'
        }
        
        // 先直接打开对话框，避免用户等待
        addMemberDialogVisible.value = true
        
        // 显示加载状态
        ElMessage({
          type: 'info',
          message: '正在加载可用成员列表...',
          duration: 2000
        })
        
        // 刷新用户列表和成员列表，确保数据是最新的
        console.log('开始刷新用户和成员数据...')
        await Promise.all([
          store.dispatch('fetchUsers'),
          store.dispatch('fetchProjectMembers', props.id)
        ])
        
        console.log('数据刷新完成')
        console.log('当前可用用户:', availableUsers.value)
        
        if (availableUsers.value.length === 0) {
          ElMessage({
            type: 'warning',
            message: '没有找到可添加的用户，所有用户可能已经是项目成员',
            duration: 5000
          })
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败，请稍后重试')
      }
    }
    
    // 提交添加成员表单
    const submitAddMemberForm = async () => {
      if (!addMemberFormRef.value) {
        console.warn('表单引用不存在，无法提交')
        return
      }
      
      console.log('提交添加成员表单', addMemberForm.value)
      
      // 检查必填字段
      if (!addMemberForm.value.user_id || !addMemberForm.value.role) {
        ElMessage.warning('请选择用户和角色')
        return
      }
      
      await addMemberFormRef.value.validate(async (valid) => {
        if (valid) {
          addingMember.value = true
          try {
            console.log('正在添加成员，数据:', {
              projectId: props.id,
              memberData: addMemberForm.value
            })
            
            const response = await store.dispatch('addProjectMember', {
              projectId: props.id,
              memberData: addMemberForm.value
            })
            
            console.log('添加成员响应:', response)
            ElMessage.success('成员添加成功')
            addMemberDialogVisible.value = false
            
            // 重新获取项目成员
            await store.dispatch('fetchProjectMembers', props.id)
          } catch (error) {
            console.error('添加成员失败:', error)
            ElMessage.error(`添加失败: ${error.message || '未知错误，请重试'}`)
          } finally {
            addingMember.value = false
          }
        } else {
          console.warn('表单验证失败')
        }
      })
    }
    
    // 移除成员
    const removeMember = async (member) => {
      try {
        await ElMessageBox.confirm(
          `确定要移除成员"${member.username}"吗？`,
          '移除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await store.dispatch('removeProjectMember', {
          projectId: props.id,
          memberId: member.id
        })
        ElMessage.success('成员移除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`移除失败: ${error.message}`)
        }
      }
    }
    
    // 设置成员为负责人
    const setAsOwner = async (member) => {
      try {
        await ElMessageBox.confirm(
          `确定要将"${member.username}"设置为负责人吗？`,
          '设置确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await store.dispatch('setProjectOwner', {
          projectId: props.id,
          memberId: member.id
        })
        ElMessage.success('负责人设置成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`设置失败: ${error.message}`)
        }
      }
    }
    
    // 判断是否为项目负责人或创建者
    const isOwnerOrCreator = computed(() => {
      if (!project.value) return false
      
      // 检查用户角色
      if (project.value.user_role === 'owner' || project.value.user_role === 'creator') {
        return true
      }
      
      // 或者检查is_owner和is_creator标志（如果可用）
      if (project.value.is_owner === true || project.value.is_creator === true) {
        return true
      }
      
      // 检查项目所有者ID是否与当前用户ID匹配
      if (project.value.owner_id && currentUserId.value && 
          project.value.owner_id.toString() === currentUserId.value.toString()) {
        return true
      }
      
      // 检查项目创建者ID是否与当前用户ID匹配
      if (project.value.creator_id && currentUserId.value && 
          project.value.creator_id.toString() === currentUserId.value.toString()) {
        return true
      }
      
      return false
    })
    
    onMounted(() => {
      fetchProjectData()
    })
    
    return {
      project,
      projectName,
      loading,
      tasks,
      tasksLoading,
      members,
      membersLoading,
      currentUserId,
      goBack,
      formatDate,
      createTaskDialogVisible,
      createTaskForm,
      createTaskRules,
      createTaskFormRef,
      showCreateTaskDialog,
      submitCreateTaskForm,
      editProjectDialogVisible,
      editProjectForm,
      editProjectRules,
      editProjectFormRef,
      showEditProjectDialog,
      submitEditProjectForm,
      addMemberDialogVisible,
      addMemberForm,
      addMemberRules,
      addMemberFormRef,
      showAddMemberDialog,
      submitAddMemberForm,
      getStatusType,
      getStatusText,
      getTaskStatusType,
      getTaskStatusText,
      confirmDeleteTask,
      viewTask,
      getUserRoleType,
      getUserRoleText,
      getMemberRoleText,
      removeMember,
      setAsOwner,
      availableUsers,
      isOwnerOrCreator,
      activeFormTab
    }
  }
}
</script>

<style scoped>
.project-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 0 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.project-info {
  margin-bottom: 30px;
}

.info-item {
  margin-bottom: 12px;
  line-height: 1.5;
}

.info-section {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.info-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-weight: 500;
  font-size: 16px;
}

.empty-git-info {
  color: #909399;
  font-style: italic;
}

.empty-info {
  color: #909399;
  font-style: italic;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.section-title {
  margin: 20px 0 10px;
}

.section-title h3 {
  margin: 0;
  font-weight: 500;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.role-tag-container {
  display: flex;
  gap: 5px;
}

.role-tag {
  padding: 2px 5px;
  border-radius: 4px;
}

/* 确保下拉选择框全宽显示 */
.full-width-select {
  width: 100%;
  display: block;
}

/* 确保表单项内容宽度适应 */
:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  padding-top: 10px;
  text-align: right;
}

/* 用户选项样式 */
.user-option {
  display: flex;
  flex-direction: column;
}

.user-option .username {
  font-weight: bold;
}

.user-option .email {
  font-size: 12px;
  color: #909399;
}
</style>

<!-- 全局样式，不使用scoped -->
<style>
/* 确保下拉菜单显示在最顶层 */
.el-select-dropdown {
  z-index: 999999 !important;
}
.el-popper {
  z-index: 999999 !important;
}
</style>